// GPS SimulatorDlg.cpp : implementation file
//

#include "stdafx.h"
#include "GPS Simulator.h"
#include "GPS SimulatorDlg.h"
#include "Serial.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CGPSSimulatorDlg dialog

CGPSSimulatorDlg::CGPSSimulatorDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CGPSSimulatorDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CGPSSimulatorDlg)
	m_strDetailsView = _T("");
	m_strFilePath = _T("");
	m_COM_Port = -1;
	m_Baud_Rate = -1;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);


}

void CGPSSimulatorDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CGPSSimulatorDlg)
	DDX_Text(pDX, IDC_DETAILS, m_strDetailsView);
	DDX_Text(pDX, IDC_FILENAME, m_strFilePath);
	DDX_Radio(pDX, IDC_COM1, m_COM_Port);
	DDX_Radio(pDX, IDC_BAUD1, m_Baud_Rate);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CGPSSimulatorDlg, CDialog)
	//{{AFX_MSG_MAP(CGPSSimulatorDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BROWSE, OnBrowse)
	ON_BN_CLICKED(IDC_WRITE, OnWrite)
	ON_BN_CLICKED(IDC_STOP, OnStop)
	ON_BN_CLICKED(IDC_EXIT, OnExit)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CGPSSimulatorDlg message handlers

BOOL CGPSSimulatorDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here

	//m_COM_Port = 0;
	//m_Baud_Rate = 0;
	m_bRunning = false;	

	return TRUE;  // return TRUE  unless you set the focus to a control

}

void CGPSSimulatorDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CGPSSimulatorDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CGPSSimulatorDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CGPSSimulatorDlg::OnBrowse() 
{
	CString path;
	CFile *filestream;
	DWORD retVal;

	CFileDialog m_dlg(TRUE, _T("TXT"), NULL, OFN_OVERWRITEPROMPT, 
		_T("Text file (TXT)|*.TXT|All Files (*.*)|*.*||"));

	index = 0;

	if (m_dlg.DoModal() == IDOK)
	{
		path = m_dlg.GetPathName();

		m_strFilePath = path;
		UpdateData(FALSE);
		
		filestream = new CFile(path, GENERIC_READ);
	
		if (filestream == NULL)
		{
			WriteLogMessage(_T("Error in Opening File!!"));			
			return;
		}

		fileSize = filestream->GetLength();

		fileBuffer = new char[fileSize];

		retVal = filestream->Read(fileBuffer, fileSize);

		if (retVal == 0)
		{
			WriteLogMessage(_T("Error in reading file or file is empty!!"));
			return;
		}		

		WriteLogMessage("File loaded into memory. Click write to start writing to device.");

		filestream->Close();
		delete filestream;

	}
	
}

void CGPSSimulatorDlg::WriteLogMessage(CString message) 
{
	if (m_strDetailsView == "")
	{
		m_strDetailsView = message;
	}
	else
	{
		m_strDetailsView = m_strDetailsView + "\r\n" + message;
	}
	
	
	UpdateData(FALSE);
}

CGPSSimulatorDlg::~CGPSSimulatorDlg()
{
	m_bRunning = false;
	delete fileBuffer;
}

char* CGPSSimulatorDlg::GetNextLine()
{

	int i=0,j=0;
	char *currLine;

	if (index <= fileSize)
	{

		while (fileBuffer[i] != 0x0D && fileBuffer[i] != 0x0A)
		{
			i++;
		}
	}
	else
	{
		return "";
	}

	currLine = new char[i];

	strncpy(currLine,fileBuffer,i);

	currLine[i] = '\0';

	fileBuffer+= i+2;
	index += i+2;

	return currLine;
	
}

void CGPSSimulatorDlg::OnWrite() 
{

	CString buffer;
	CSerial serial;		
	CSerial::EBaudrate baudRate;
	CSerial::EPort portAvailability;
	DWORD iBytesWritten;

	char * strCOMPort = new char[4];

	m_bRunning = true;
	
	sprintf(strCOMPort, "COM%d", m_COM_Port+1);

	switch(m_Baud_Rate)
	{
	case 0:
		baudRate = CSerial::EBaud2400;
		break;
	case 1:
		baudRate = CSerial::EBaud4800;
		break;
	case 2:
		baudRate = CSerial::EBaud9600;
		break;
	case 3:
		baudRate = CSerial::EBaud14400;
		break;	
	}

	portAvailability = serial.IsPortAvailable(strCOMPort);

	if (portAvailability == CSerial::EPortAvailable )
	{
	}
	else if (portAvailability == CSerial::EPortNotAvailable)
	{
		AfxMessageBox(strcat(strCOMPort, " is not present"));
		return;
	}
	else if (portAvailability == CSerial::EPortInUse)
	{
		AfxMessageBox(strcat(strCOMPort, " is in use"));
		return;
	}

	if (serial.Open(strCOMPort,128,128) != ERROR_SUCCESS)
	{
		AfxMessageBox(strcat("Error opening " , strCOMPort));
		return;
	}

	if (serial.Setup(baudRate,CSerial::EData8,CSerial::EParNone,CSerial::EStop1) != ERROR_SUCCESS)
	{
		AfxMessageBox(strcat("Error initializing port ",  strCOMPort));
		return;
	}
	

	while((buffer = GetNextLine()) != "" && m_bRunning == true)
	{
		if ( "$GPGGA" == buffer.Left(6))
		{			
			if (serial.Write(buffer + "\r\n", &iBytesWritten) == ERROR_SUCCESS)
			{
				WriteLogMessage(buffer);			
			}
			else
			{
				AfxMessageBox(strcat("Error writing data to " , strCOMPort));
				return;
			}

		}

	} 	
	
	//serial.Write(_T("test"), &iBytesWritten);
	serial.Close();  

}


void CGPSSimulatorDlg::OnStop() 
{
	// TODO: Add your control notification handler code here
	m_bRunning = false;	
}

void CGPSSimulatorDlg::OnExit() 
{
	// TODO: Add your control notification handler code here
	m_bRunning = false;
	//delete fileBuffer;

	CGPSSimulatorDlg::OnOK();	

}

BOOL CGPSSimulatorDlg::DestroyWindow() 
{
	// TODO: Add your specialized code here and/or call the base class
	m_bRunning = false;
	return CDialog::DestroyWindow();
}
